package com.bjpowernode.controller;

import com.bjpowernode.beans.Stu;
import com.bjpowernode.exception.MyRangeException;
import com.bjpowernode.services.StuServices;
import com.bjpowernode.services.StuServicesImp;
import com.sun.deploy.util.FXLoader;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Optional;
import java.util.ResourceBundle;


//绑定了app.fxml界面
//我们需要app.fxml界面启动的时候，立即触发一个事件（主要用于初始化）

//1——需要在控制器上实现一个接口Initializable
//2——需要实现一个方法initialize方法
public class AppController implements Initializable {
    StuServices stuServices = new StuServicesImp();
    Alert alert = null;

    @FXML
    private Button btnMenuClassRoom;
    @FXML
    private Button btnMenuStu;
    @FXML
    private Button btnMenuExit;
    @FXML
    private Button btnSelecAllStu;

    @FXML
    private Button btnEditStu;

    @FXML
    private Button btnCallName;

    @FXML
    private TextField tNum;

    @FXML
    private Button btnDelStu;

    @FXML
    private Button btnAddStu;


    @FXML
    private TableView<Stu> tableViewStu;

    @FXML
    private TableColumn<Stu, Integer> cId;

    @FXML
    private TableColumn<Stu, String> cName;

    @FXML
    private TableColumn<Stu, String> cSex;

    @FXML
    private TableColumn<Stu, String> cAge;

    @FXML
    private TableColumn<Stu, Float> cScore;


    //todo 添加
    @FXML
    void btnAddStuAction(ActionEvent event) throws IOException {

        //弹出模态框dialog
        //模态框内容
        DialogPane dialogPane = new DialogPane();
        //中间内容区
        //dialogPane.setContentText("xxxxxxxx");
        //中间内容自定义
        URL resource = AppController.class.getResource("/view/stuAdd.fxml");
        Parent parent = FXMLLoader.load(resource);
        dialogPane.setGraphic(parent);
        //底部按钮区
        dialogPane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
        //模态框外壳
        Dialog<ButtonType> dialog = new Dialog<>();
        //头部标题区
        dialog.setTitle("学生信息添加");
        //模态框设置内容
        dialog.setDialogPane(dialogPane);
        //模态框弹出,并且等待你点击之后继续执行
        Optional<ButtonType> buttonType = dialog.showAndWait();
        if (buttonType.get() == ButtonType.OK) {
            //添加学生操作
            Stu stu = new Stu();
            //跨控制器找对象，找根布局对象的lookup方法即可
            TextField tName = (TextField) parent.lookup("#tName");
            TextField tAge = (TextField) parent.lookup("#tAge");
            TextField tScore = (TextField) parent.lookup("#tScore");
            RadioButton rSexM = (RadioButton) parent.lookup("#rSexM");
            RadioButton rSexW = (RadioButton) parent.lookup("#rSexW");
            stu.setName(tName.getText());
            if (rSexM.isSelected()) {
                stu.setSex("M");
            } else {
                stu.setSex("W");
            }
            stu.setAge(tAge.getText());

            try {
                stu.setScore(Float.valueOf(tScore.getText()));
            } catch (NumberFormatException e) {
                alert = new Alert(Alert.AlertType.ERROR, "输入的不是数字", ButtonType.OK);
                alert.show();
                return;
            }

            boolean add = false;
            try {
                add = stuServices.add(stu);
            } catch (MyRangeException e) {
                alert = new Alert(Alert.AlertType.ERROR, e.getMessage(), ButtonType.OK);
                alert.show();
                return;
            }

            if (!add) {
                System.out.println("添加失败");
                return;
            }

            //刷新
            getAll();
        }


    }

    //todo 修改
    @FXML
    void btnEditStuAction(ActionEvent event) throws IOException {

        TableView.TableViewSelectionModel<Stu> selectionModel = tableViewStu.getSelectionModel();
        //这里的学生对象就是集合里面的对象
        Stu stu = selectionModel.getSelectedItem();
        if (stu == null) {
            alert = new Alert(Alert.AlertType.INFORMATION, "你没有选中一行", ButtonType.OK);
            alert.show();
            return;
        }

        //弹出修改框
        DialogPane dialogPane = new DialogPane();
        URL resource = AppController.class.getResource("/view/stuAdd.fxml");
        Parent parent = FXMLLoader.load(resource);
        dialogPane.setGraphic(parent);
        dialogPane.getButtonTypes().addAll(ButtonType.YES, ButtonType.NO);

        TextField tName = (TextField) parent.lookup("#tName");
        TextField tAge = (TextField) parent.lookup("#tAge");
        TextField tScore = (TextField) parent.lookup("#tScore");
        RadioButton rSexM = (RadioButton) parent.lookup("#rSexM");
        RadioButton rSexW = (RadioButton) parent.lookup("#rSexW");
        tName.setText(stu.getName());
        tAge.setText(stu.getAge());
        tScore.setText(String.valueOf(stu.getScore()));
        String sex = stu.getSex();
        if (sex.equals("M")) {
            rSexM.setSelected(true);
        } else {
            rSexW.setSelected(true);
        }

        Dialog<ButtonType> dialog = new Dialog<>();
        dialog.setTitle("学习信息修改");
        dialog.setDialogPane(dialogPane);
        Optional<ButtonType> buttonType = dialog.showAndWait();


        //临时学生
        Stu tempStu = new Stu();
        if (buttonType.get() == ButtonType.YES) {
            //学生对象属性的改变
            //由于stu就是集合里面的对象，这里没有验证，因此不能直接设置

            tempStu.setName(tName.getText());
            tempStu.setAge(tAge.getText());

            try {
                tempStu.setScore(Float.valueOf(tScore.getText()));
            } catch (NumberFormatException e) {
                alert = new Alert(Alert.AlertType.ERROR, "输入的不是个数字", ButtonType.OK);
                alert.show();
                return;
            }
            tempStu.setSex(rSexM.isSelected() ? "M" : "W");

            try {
                //这里需要验证临时学生对象tempStu
                tempStu.validation();
            } catch (MyRangeException e) {
                alert = new Alert(Alert.AlertType.ERROR, e.getMessage(), ButtonType.OK);
                alert.show();
                return;
            }

            //验证通过，则交换学生
            //把tempStu的属性交换给stu
            stu.setName(tempStu.getName());
            stu.setAge(tempStu.getAge());
            stu.setSex(tempStu.getSex());
            stu.setScore(tempStu.getScore());

            //交给业务
            boolean edit = false;
            edit = stuServices.edit(stu);
            if (!edit) {
                alert = new Alert(Alert.AlertType.ERROR, "修改错误", ButtonType.OK);
                alert.show();
                return;
            }
            getAll();
        }
    }

    //todo 删除
    @FXML
    void btnDelStuAction(ActionEvent event) {

        //获取选择的模型
        TableView.TableViewSelectionModel<Stu> selectionModel = tableViewStu.getSelectionModel();
        //获取选择的学生
        Stu stu = selectionModel.getSelectedItem();
        if (stu == null) {
            alert = new Alert(Alert.AlertType.ERROR, "你没有选择一行学生", ButtonType.OK);
            alert.show();
            return;
        }
        alert = new Alert(Alert.AlertType.INFORMATION, "是否删除?", ButtonType.OK, ButtonType.CANCEL);
        Optional<ButtonType> buttonType = alert.showAndWait();
        if (buttonType.get() == ButtonType.OK) {
            //删除学生
            boolean del = stuServices.del(stu);
            //删除失败
            if (!del) {
                alert = new Alert(Alert.AlertType.ERROR, "删除失败", ButtonType.OK);
                alert.show();
                return;
            }
            //删除成功
            getAll();
        }


    }


    @FXML
    void btnMenuClassRoomAction(ActionEvent event) {

    }

    @FXML
    void btnMenuExitAction(ActionEvent event) {
        System.exit(0);
    }


    @FXML
    void btnMenuStuAction(ActionEvent event) {

    }


    //todo 全查
    @FXML
    void btnSelectAllStuAction(ActionEvent event) {
        getAll();
    }


    //todo 点名
    @FXML
    void btnCallNameAction(ActionEvent event) {


        //点名输入的人数，控制器只负责输入的是不是数字
        int num = 0;
        try {
            num = Integer.valueOf(tNum.getText());
        } catch (NumberFormatException e) {
            alert = new Alert(Alert.AlertType.ERROR, "请输入整数", ButtonType.OK);
            alert.show();
            return;
        }

        ArrayList<Stu> result = null;
        try {
            //控制器捕获并处理业务向上抛出的异常
            result = stuServices.call(num);
        } catch (MyRangeException e) {
            alert = new Alert(Alert.AlertType.ERROR, e.getMessage(), ButtonType.OK);
            alert.show();
            return;
        }

//        String temp="";
//        for (Stu stu : result) {
//            temp+="学号：";
//            temp+=stu.getId();
//            temp+="  ";
//            temp+="姓名：";
//            temp+=stu.getName();
//            temp+="\n";
//        }

        StringBuffer stringBuffer = new StringBuffer();
        for (Stu stu : result) {
            stringBuffer.append("学号：");
            stringBuffer.append(stu.getId());
            stringBuffer.append("  ");
            stringBuffer.append("姓名：");
            stringBuffer.append(stu.getName());
            stringBuffer.append("\n");
        }
        String info = stringBuffer.toString();
        alert = new Alert(Alert.AlertType.INFORMATION, info, ButtonType.OK);
        alert.show();
    }


    //todo 初始化
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //数据列绑定实体beans属性
        cId.setCellValueFactory(new PropertyValueFactory<Stu, Integer>("id"));
        cName.setCellValueFactory(new PropertyValueFactory<Stu, String>("name"));
        cSex.setCellValueFactory(new PropertyValueFactory<Stu, String>("sex"));
        cAge.setCellValueFactory(new PropertyValueFactory<Stu, String>("age"));
        cScore.setCellValueFactory(new PropertyValueFactory<Stu, Float>("score"));

        getAll();
    }


    //todo 查询所有封装方法
    private void getAll() {
        //表格的集合需要清空【不然修改无法响应】
        tableViewStu.getItems().clear();
        //获取DB.stus
        ArrayList<Stu> all = stuServices.getAll();
        //转换成表格看得懂的集合，这里是引用关系，而不是拷贝关系
        ObservableList<Stu> stus = FXCollections.observableArrayList(all);
        tableViewStu.setItems(stus);
    }


}
